package com.example.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.example.mapper.UserMapper;
import com.example.entity.User;
import com.example.exception.BusinessException;

@Service
public class AuthService {

    private static final Logger logger = LoggerFactory.getLogger(AuthService.class);
    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Autowired
    private UserMapper userMapper;

    public boolean authenticate(String phone, String password) {
        if (phone == null || phone.trim().isEmpty()) {
            throw new BusinessException.ValidationException("手机号不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            throw new BusinessException.ValidationException("密码不能为空");
        }
        
        try {
            // 先查询手机号是否存在
            User user = userMapper.findByPhone(phone);
            if (user == null) {
                logger.info("手机号 {} 在数据库中不存在", phone);
                return false;
            }

            // 查询手机号对应的密码并比较（支持加密和明文密码）
            String dbPassword = user.getPassword();
            if (dbPassword != null) {
                // 如果是BCrypt加密的密码，使用BCrypt验证
                if (dbPassword.startsWith("$2a$") || dbPassword.startsWith("$2b$") || dbPassword.startsWith("$2y$")) {
                    boolean matches = passwordEncoder.matches(password, dbPassword);
                    if (matches) {
                        logger.info("手机号 {} 验证成功（加密密码）", phone);
                        return true;
                    }
                } else {
                    // 兼容明文密码（建议逐步迁移到加密密码）
                    if (dbPassword.equals(password)) {
                        logger.info("手机号 {} 验证成功（明文密码）", phone);
                        return true;
                    }
                }
            }
            
            logger.info("手机号 {} 对应的密码验证失败", phone);
            return false;
        } catch (Exception e) {
            logger.error("用户认证过程中发生异常", e);
            throw new BusinessException("认证过程中发生错误", e);
        }
    }
    
    // 添加获取用户信息的方法
    public User getUserByPhone(String phone) {
        if (phone == null || phone.trim().isEmpty()) {
            throw new BusinessException.ValidationException("手机号不能为空");
        }
        
        try {
            User user = userMapper.findByPhone(phone);
            if (user == null) {
                throw new BusinessException.DataNotFoundException("用户不存在");
            }
            return user;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            logger.error("查询用户信息时发生异常", e);
            throw new BusinessException("查询用户信息失败", e);
        }
    }
    
    // 密码加密方法
    public String encodePassword(String rawPassword) {
        if (rawPassword == null || rawPassword.trim().isEmpty()) {
            throw new BusinessException.ValidationException("密码不能为空");
        }
        return passwordEncoder.encode(rawPassword);
    }
    
    // 验证密码强度
    public boolean isPasswordStrong(String password) {
        if (password == null || password.length() < 6) {
            return false;
        }
        // 可以添加更复杂的密码强度验证逻辑
        return true;
    }
}
